/*
 * Copyright (C) 2007  Vianney le Clément
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package fsahoraires.cours;

import java.util.*;

public class CompoundHoraire implements Horaire {

	/**
	 * Les listes des occupations. L'index correspond à
	 * <code>jour.ordinal()*TRANCHES + tranche</code>
	 */
	private List<Occupation>[] horaire;
	private int occupations, heuresParSemaine;

	private int convertKey(Jour jour, int tranche) {
		return jour.ordinal() * TRANCHES + tranche;
	}

	@SuppressWarnings("unchecked")
	public CompoundHoraire() {
		int size = TRANCHES * Jour.values().length;
		horaire = new List[size];
		for (int i = 0; i < size; i++)
			horaire[i] = new ArrayList<Occupation>();
		occupations = 0;
		heuresParSemaine = 0;
	}

	public List<Occupation> getOccupations(Jour jour, int tranche) {
		return Collections.unmodifiableList(horaire[convertKey(jour, tranche)]);
	}

	public int getOccupationsCount() {
		return occupations;
	}

	public int getHeuresParSemaine() {
		return heuresParSemaine;
	}

	public void add(Occupation o, Jour jour, int tranche) {
		if (o == null || jour == null)
			throw new IllegalArgumentException(
					"occupation et jour ne peuvent pas être null");
		if (tranche < 0 || tranche > TRANCHES)
			throw new IllegalArgumentException(
					"tranche doit être compris entre 0 et TRANCHES-1");
		List<Occupation> list = horaire[convertKey(jour, tranche)];
		if (list.size() == 0 && o.getSemaines().get(1))
			heuresParSemaine += 2;
		list.add(o);
		occupations++;
	}

	public void add(Horaire h) {
		for (Jour jour : Jour.values()) {
			for (int tranche = 0; tranche < Horaire.TRANCHES; tranche++) {
				for (Occupation occupation : h.getOccupations(jour, tranche)) {
					add(occupation, jour, tranche);
				}
			}
		}
	}
}
